
import { Response, NextFunction } from 'express';
import Db from './../db';

export const orders = async (req: any, res: Response, next: NextFunction) => {
  try {
    let { goodsId } = req.body;
    const userId = req['userId'];
    // 查询该用户是否已经下单了
    const isExist = await Db.query('select count(*) as count from orders where user_id = ?', [userId]);
    console.log(userId, '??=====>', isExist[0].count)
    if (isExist && isExist[0].count) {
      console.log('进来了')
      res.json({
        code: 1,
        message: '不能重复下单',
      })
      return;
    }
    console.log('继续走了')
    // 根据当前商品id去查询商品表当时的价格
    const goodsInfo = await Db.query('select price from goods where id = ? limit 1;', [goodsId]);
    console.log(goodsInfo, '商品')
    if (goodsInfo && goodsInfo.length) {
      const price = goodsInfo[0].price;
      const { affectedRows } = await Db.query(`insert into orders(goods_id, price, user_id) values(?, ?, ?)`, [goodsId, price, userId]);
      if (affectedRows) {
        res.json({
          code: 0,
          message: '下单成功',
        })
        return;
      } else {
        res.json({
          code: 1,
          message: '下单失败',
        })
        return;
      }
    } else {
      res.json({
        code: 1,
        message: '商品不存在',
      })
      return;
    }
  } catch (error) {
    next(error);
  };
}